"use strict";

import Vue from 'vue';
import axios from "axios";
import router from '@/router';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    let token=sessionStorage.getItem("token");
    if(token)
       config.headers.jwt_token=sessionStorage.getItem("token");
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    console.log(response);
   
    if(response.status==200){
        let state=response.data.state;
        switch(state){
          case 401:
              sessionStorage.removeItem("curUser");
              sessionStorage.removeItem("token");
              alert('hh')
              router.push("/login");
              return new Promise(()=>{});
          case 403:router.push("/deney");return new Promise(()=>{});
          case 500:router.push("/error");return new Promise(()=>{});
          default:break;
        }
    }
    return response;
  },
  function(error) {
    console.log(error);
    router.push("/error");
    return Promise.reject(error);
  }
);

export default _axios;

// Plugin.install = function(Vue, options) {
//   Vue.axios = _axios;
//   window.axios = _axios;
//   Object.defineProperties(Vue.prototype, {
//     axios: {
//       get() {
//         return _axios;
//       }
//     },
//     $axios: {
//       get() {
//         return _axios;
//       }
//     },
//   });
// };

// Vue.use(Plugin)

//export default Plugin;
